using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ERPBackend.Models;
using ERPBackend.Services;

namespace ERPBackend.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EBOMsController : ControllerBase
    {
        private readonly IEBOMService _ebomService;

        public EBOMsController(IEBOMService ebomService)
        {
            _ebomService = ebomService ?? throw new ArgumentNullException(nameof(ebomService));
        }

        // GET: api/EBOMs
        [HttpGet]
        public async Task<ActionResult<IEnumerable<EBOM>>> GetEBOMs()
        {
            var eboms = await _ebomService.GetAllEBOMsAsync();
            return Ok(eboms);
        }

        // GET: api/EBOMs/5
        [HttpGet("{id}")]
        public async Task<ActionResult<EBOM>> GetEBOM(int id)
        {
            var ebom = await _ebomService.GetEBOMByIdAsync(id);

            if (ebom == null)
            {
                return NotFound();
            }

            return Ok(ebom);
        }

        // GET: api/EBOMs/code/{bomCode}/version/{version}
        [HttpGet("code/{bomCode}/version/{version}")]
        public async Task<ActionResult<EBOM>> GetEBOMByCodeAndVersion(string bomCode, string version)
        {
            var ebom = await _ebomService.GetEBOMByCodeAndVersionAsync(bomCode, version);

            if (ebom == null)
            {
                return NotFound();
            }

            return Ok(ebom);
        }

        // GET: api/EBOMs/material/{materialId}
        [HttpGet("material/{materialId}")]
        public async Task<ActionResult<IEnumerable<EBOM>>> GetEBOMsByMaterial(int materialId)
        {
            var eboms = await _ebomService.GetEBOMsByMaterialIdAsync(materialId);
            return Ok(eboms);
        }

        // GET: api/EBOMs/search?bomCode={code}&materialName={name}&status={status}
        [HttpGet("search")]
        public async Task<ActionResult<IEnumerable<EBOM>>> SearchEBOMs(
            [FromQuery] string bomCode,
            [FromQuery] string materialName,
            [FromQuery] string status)
        {
            var eboms = await _ebomService.SearchEBOMsAsync(bomCode, materialName, status);
            return Ok(eboms);
        }

        // POST: api/EBOMs
        [HttpPost]
        public async Task<ActionResult<EBOM>> PostEBOM(EBOM ebom)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            try
            {
                var createdEBOM = await _ebomService.CreateEBOMAsync(ebom);
                return CreatedAtAction("GetEBOM", new { id = createdEBOM.Id }, createdEBOM);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
        }

        // PUT: api/EBOMs/5
        [HttpPut("{id}")]
        public async Task<IActionResult> PutEBOM(int id, EBOM ebom)
        {
            if (id != ebom.Id)
            {
                return BadRequest();
            }

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            try
            {
                var updated = await _ebomService.UpdateEBOMAsync(ebom);
                if (!updated)
                {
                    return NotFound();
                }
                return NoContent();
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
        }

        // DELETE: api/EBOMs/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteEBOM(int id)
        {
            var deleted = await _ebomService.DeleteEBOMAsync(id);
            if (!deleted)
            {
                return NotFound();
            }
            return NoContent();
        }

        // PATCH: api/EBOMs/5/approve
        [HttpPatch("{id}/approve")]
        public async Task<IActionResult> ApproveEBOM(int id, [FromQuery] int approvedBy)
        {
            var approved = await _ebomService.ApproveEBOMAsync(id, approvedBy);
            if (!approved)
            {
                return NotFound();
            }
            return NoContent();
        }

        // PATCH: api/EBOMs/5/enable
        [HttpPatch("{id}/enable")]
        public async Task<IActionResult> EnableEBOM(int id, [FromQuery] int enabledBy)
        {
            var enabled = await _ebomService.EnableEBOMAsync(id, enabledBy);
            if (!enabled)
            {
                return NotFound();
            }
            return NoContent();
        }

        // PATCH: api/EBOMs/5/disable
        [HttpPatch("{id}/disable")]
        public async Task<IActionResult> DisableEBOM(int id, [FromQuery] int disabledBy)
        {
            var disabled = await _ebomService.DisableEBOMAsync(id, disabledBy);
            if (!disabled)
            {
                return NotFound();
            }
            return NoContent();
        }

        // POST: api/EBOMs/{id}/new-version
        [HttpPost("{id}/new-version")]
        public async Task<ActionResult<EBOM>> CreateNewVersion(int id, [FromQuery] string newVersion, [FromQuery] int createdBy, [FromQuery] string changeReason)
        {
            try
            {
                var newEBOM = await _ebomService.CreateNewVersionAsync(id, newVersion, createdBy, changeReason);
                return CreatedAtAction("GetEBOM", new { id = newEBOM.Id }, newEBOM);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
        }
    }
}